package atest.reopen.session.interceptor;

import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;

/**
 * mybatis 支持Executor、ParameterHandler、ResultSetHandler、StatementHandler过程的拦截
 * http://www.mybatis.org/mybatis-3/zh/configuration.html#plugins，
 * 
 * 
 * 如果有多个重复的slave库，实现负载均衡可以自定义一个RoutingDataSource，
 * 参考：http://blog.csdn.net/keda8997110/article/details/16827215
 * @author zenghua233
 *
 */
@Intercepts({@Signature(
		  type= Executor.class,
		  method = "query",
		  args = {MappedStatement.class,Object.class, RowBounds.class,ResultHandler.class})})
public class MyInterceptor implements Interceptor {
	public final Logger mylog = Logger.getLogger(MyInterceptor.class);
	
	public ConcurrentHashMap<String, Environment> map = new ConcurrentHashMap<>();

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
		System.out.println("执行intercept");
		mylog.debug("MyInterceptor执行拦截操作");
		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
		Configuration configuration = mappedStatement.getConfiguration();
		
		if (map.get("slave") == null) {
			Environment defaultEnvironment = configuration.getEnvironment();
			
			//设置从库的环境,dataSource不能设置为空
//			Environment.Builder environmentBuilder = new Environment.Builder(defaultEnvironment.getId())
//		              .transactionFactory(defaultEnvironment.getTransactionFactory())
//		              .dataSource(null);
			
//			Environment slave = environmentBuilder.build();
//			map.put("slave", slave);
		}
		
		configuration.setEnvironment(map.get("slave"));
		return invocation.proceed();
	}

	@Override
	public Object plugin(Object target) {
		//将目标对象封装成代理对象
		return Plugin.wrap(target, this);
	}

	@Override
	public void setProperties(Properties properties) {
	}

}
